<template>
  <div class="reporthead">
    <div class="head-row">
      <span class="choice-title">所属企业：</span>
      <el-cascader
        v-model="company_id_arr"
        :placeholder="'选择所属企业'"
        collapse-tags
        :options="options"
        ref="cascaderRef"
        :props="{
          expandTrigger: 'hover',
          multiple: 'true',
         }"
        clearable
        @visible-change="companyVisibleChange"
        @remove-tag="companyRemoveTag"
        size="small"
        style="width:450px">
      </el-cascader>
    </div>
    <div class="head-row site-row">
      <!--案场名称-->
      <span class="choice-title">案场选择：</span>
      <div class="site">
        <el-select v-model="submitCase"
                   @change="CaseChange"
                   @visible-change="CaseVisibleChange"
                   @remove-tag="CaseClick"
                   filterable
                   multiple
                   collapse-tags
                   size="small"
                   placeholder="请选择位置"
                   style="width:450px;">
          <el-option
            v-for="item in Case"
            :key="item.id"
            :label="item.case_name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="head-row" style="height: auto; min-height: 36px;">
      <div class="datecheck">
        <span>日期选择：</span>
        <el-date-picker
          v-model="datetimeval.day"
          type="daterange"
          align="right"
          unlink-panels
          popper-class="report-date"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="dayChange"
        >
        </el-date-picker>
        <span style="margin-left: 28px;">时段选择：</span>
        <template>
          <el-time-picker
            is-range
            v-model="datetimeval.hm"
            value-format="HH:mm"
            format="HH:mm"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            @change="timeChange">
          </el-time-picker>
        </template>
        <el-select v-model="TimeFast" placeholder="快速选择" :disabled="isDisabledTims" @change="TimaFastChange" class="timefast">
          <el-option
            v-for="item in TimeFastList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="head-row-sub">
      <el-button @click="queryData"
                 style="margin-right:45px;"
                 :type="dataIsChange ? 'primary':'success'" size="small">
        <span v-if="dataIsChange"><i class="el-icon-search"></i> 查询报表</span>
        <span v-else><i class="el-icon-refresh-left"></i> 刷新报表</span>
      </el-button>
    </div>
  </div>
</template>
<style lang="scss">
  .reporthead {
    width: 100%;
    background: #fff;
    padding: 27px 0 20px 45px;
    .head-row {
      line-height: 36px;
      height: 36px;
      margin-bottom: 15px;
      .choice-title{
        display: inline-block;
        width: 85px;
        margin-right: 5px;
        text-align: left;
      }
      .block{
        color: #777;
        span{
          margin-right: 2px;
        }
      }
      span {
        font-size: 14px;
      }
      .datecheck {
        .el-input__inner {
          line-height: 36px;
          height: 36px;
          font-size: 14px;
          border-radius: 0;
          width: 250px;
          border-color: #e3eaf4;
          .el-input__icon {
            height: 36px;
            line-height: 36px;
            &.el-range__close-icon {
              display: none;
            }
          }
          .el-range-separator {
            height: 36px;
            line-height: 36px;
            padding: 0;
            width:6%;
          }
        }
        height: 36px;
        display: inline-block;
        .el-date-editor--date {
          .el-input__inner {
            border-radius: 0;
            border-color: #e3eaf4;
            height: 36px;
            line-height: 36px;
          }
          span,
          i {
            line-height: 36px;
          }
        }

        .timefast {
          width: 120px;
          .el-input__inner {
            padding: 0 20px;
            font-size: 14px;
            margin-left: -6px;
          }
        }
        .el-input--suffix {
          width: 120px;
          .el-input__inner {
            padding-right: 0;
            width: 120px;
          }
          .el-input__inner::-webkit-input-placeholder{
            color: #545deb;
          }
          .el-input__prefix {
            .el-input__icon {
              line-height: 36px;
              height: 36px;
            }
          }
          .el-input__suffix {
            line-height: 45px;
            vertical-align: middle;
            .el-input__suffix-inner{
              .el-icon-arrow-up.is-reverse{
                margin-top: -2px;
                display: block;
              }
            }
          }
        }
      }
      &.site-row {
        margin-bottom: 3px;
        position: relative;
        height: auto;
        > span {
          vertical-align: top;
        }
        .xiala {
          position: absolute;
          right: 20px;
          width: 80px;
          height: 36px;
          .iconfont {
            position: absolute;
            height: 36px;
            line-height: 38px;
            right: 10px;
          }
          .el-checkbox {
            width: 80px;
            height: 36px;
            line-height: 36px;
            padding: 0 10px 0 0;
            color: #000;
            .el-checkbox__input {
              display: none;
            }
            .el-checkbox__label {
              line-height: 36px;
              color: #000;
              padding: 0;
            }
          }

          border-radius: 2px;

          top: 0;
          text-align: center;
        }
        .site,
        .reheadselect {
          display: inline-block;
          width: 60%;
          transition: all 0.5s;
          overflow: hidden;
          &.siteopen{
            overflow-y:auto;
            &::-webkit-scrollbar {/*滚动条整体样式*/
              width: 5px;     /*高宽分别对应横竖滚动条的尺寸*/
              height: 5px;
              border-radius: 5px;
              scrollbar-arrow-color:red;
            }
            &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
              border-radius: 5px;
              box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
              background: rgba(0,0,0,0.2);
              scrollbar-arrow-color:red;
            }
            &::-webkit-scrollbar-track {/*滚动条里面轨道*/
              box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
              background: rgba(0,0,0,0.1);
              border-radius: 5px;
            }
          }
          /*.el-checkbox,.el-radio {*/
          /*width: 182px;*/
          /*margin: 0 10px 15px 0;*/
          /*padding: 0;*/
          /*height: 36px;*/
          /*line-height: 36px;*/
          /*padding: 0;*/
          /*border-radius: 2px;*/
          /*text-align: center;*/
          /*border-color: #e3eaf4;*/
          /*&.is-checked {*/
          /*border-color: #5580ff;*/
          /*background: #5580ff;*/
          /*.el-checkbox__label ,.el-radio__label{*/
          /*color: #fff;*/
          /*}*/
          /*}*/

          /*&:hover {*/
          /*border-color: #5580ff;*/
          /*}*/
          /*.el-checkbox__input,.el-radio__input {*/
          /*display: none;*/
          /*}*/
          /*.el-checkbox__label,.el-radio__label {*/
          /*padding-left: 0;*/
          /*color: #000;*/
          /*}*/
          /*}*/
        }
      }
      &.show {
        > span {
          vertical-align: bottom;
        }
        height: 24px;
        line-height: 24px;
        .el-radio-group {
          height: 24px;
          line-height: 24px;
          .el-radio-button__inner {
            height: 24px;
            line-height: 22px;
            padding: 0;
            width: 50px;
            font-size: 12px;
          }
        }
        .reload {
          width: 26px;
          line-height: 24px;
          height: 24px;
          vertical-align: middle;
          padding: 0;
          display: inline-block;
          // background-color: #8EC5FC;
          // background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
          // border-color: #8EC5FC;
          background:#ffc02e;border-color:#ffc02e;

        }
      }
    }
    .head-row-sub{
      text-align: center;
    }
  }

  .report-date.el-picker-panel{
    left: 215px !important;
    .el-picker-panel__sidebar {
      right: 0;
      width: 180px;
      text-align: center;
      &::before {
        content: "快速选择";
        width: 90%;
        height: 32px;
        margin: 8px 0;
        display: inline-block;
        font-size: 14px;
        line-height: 32px;
        border-radius: 3px;
        color: #fff;
        background: #6689f1;
        text-align: center;
      }
      .el-picker-panel__shortcut {
        text-align: center;
        display: inline-block;
        background: #f3f3f3;
        padding: 0;
        width: 40%;
        margin: 5px;
        &:hover {
          background: #5580ff;
          color: #fff;
        }
      }
    }
    .el-picker-panel__body {
      margin: 0 180px 0 0;
    }
  }

</style>
<script>
  let moment = require("moment");
  import Cascader from "@/components/sys/assembly/elcascader"; //级联选择器
  export default {
    props: {
      option: {
        type: Object,
        default: function() {
          return {
            title: "",
          };
        }
      },

      tags:{                      //区域标签ID
        default(){
          []
        }
      },
      datetimeval:{
        type:Object,
        default(){
          return { day:[moment(new Date()).format("YYYY-MM-DD"),moment(new Date()).format("YYYY-MM-DD")],hm:['00:00','23:59']}
        }
      },
      isDisabledTims:{
        default:false
      }

    },
    data() {
      return {
        pickerOptions: {                //时间日期控件规则
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6;   //正常 今天之前
          },
          shortcuts:[
            {
              text: "今天",
              onClick(picker) {
                const start = moment().format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "昨天",
              onClick(picker) {
                const start = moment()
                .subtract(1, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "前天",
              onClick(picker) {
                const start = moment()
                .subtract(2, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(2, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上周同日",
              onClick(picker) {
                const start = moment()
                .subtract(1, "weeks")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "weeks")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上月同日",
              onClick(picker) {
                const start = moment()
                .subtract(1, "months")
                .format("YYYY-MM-DD");
                const end = moment()
                .subtract(1, "months")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本周",
              onClick(picker) {
                const weekOfday = moment().format("E"); //计算今天是这周第几天
                const start = moment()
                .subtract(weekOfday - 1, "days")
                .format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一周",
              onClick(picker) {
                const start = moment()
                .week(moment().week() - 1)
                .startOf("week")
                .subtract(-1, "days")
                .format("YYYY-MM-DD");
                const end = moment()
                .week(moment().week() - 1)
                .endOf("week")
                .subtract(-1, "days")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本月",
              onClick(picker) {
                const start = moment().month(moment().month()).startOf("month").format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一月",
              onClick(picker) {
                const start = moment()
                .month(moment().month() - 1)
                .startOf("month")
                .format("YYYY-MM-DD");
                const end = moment()
                .month(moment().month() - 1)
                .endOf("month")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "本年度",
              onClick(picker) {
                const start = moment()
                .year(moment().year())
                .startOf("year")
                .format("YYYY-MM-DD");
                const end = moment().format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "上一年",
              onClick(picker) {
                const start = moment()
                .year(moment().year() - 1)
                .startOf("year")
                .format("YYYY-MM-DD");
                const end = moment()
                .year(moment().year() - 1)
                .endOf("year")
                .format("YYYY-MM-DD");
                picker.$emit("pick", [start, end]);
              }
            },
          ],
        },

        TimeFast:'',          //时间快速选择
        TimeFastList:[         //时间快速选择列表
          { label:'最近30分钟',value:'min30' },
          { label:'最近1小时',value:'hour1' },
          { label:'最近2小时',value:'hour2' },
          { label:'全天',value:'today' },
        ],

        sum_or_part: "sum",       //显示 默认合计
        company_id_arr:[],   //所属企业选中id
        company_id:'',  //所属企业选中id
        options:[],         //级联控件 所属企业

        Case:[],     //案场列表
        submitCase:null,   //案场选中参数
        showType:'time',   //显示类型

        isAllCase:true,//是否全选案场
        allCaseArr:[],//全选案场id数组

        dataIsChange:true,//判断条件是否已经变化，如果变化了，就显示查询报表按钮
      };
    },
    components: {
      Cascader
    },
    created() {},
    mounted() {
      this.getReady();
    },
    beforeDestroy(){},
    methods: {
      //页面初始化,获取企业信息，拿到第一个企业调用获取案场
      getReady(){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data => {
          if(data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list ? val[i].parent_name_list.join('/') : '';
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            this.$nextTick(()=>{
              let arr = [];
              recursionData(Array.of(data.data[0]))
              function recursionData(val) {
                if(val.length){
                  for(let i in val){
                    if(val[i].children){
                      recursionData(val[i].children)
                    }else{
                      arr.push(val[i].node_location.split('-').slice(0,-1))
                      delete val[i].children
                    }
                  }
                }
              }
              this.options = data.data;
              let company_id_arr = [];//配置当前第一个选中的值
              arr.map(x=>{
                for(let i = 0 ; i < x.length;i++){
                  if(x[i] == data.data[0].id){
                    company_id_arr.push(x.slice(i,x.length))
                  }
                }
              });
              this.company_id_arr = company_id_arr;
              this.company_id = company_id_arr.join(',');
              this.getCaseApi(company_id_arr);
            })
          }
        })
        .catch(err=>{
          console.log(err,'企业');
          this.options = [];
        })
      },
      //get案场列表api
      getCaseApi(arr,org_type=1){
        // console.log(arr,'arr');
        let lsarr=[];
        for(let i in arr) {
          lsarr.push(arr[i][arr[i].length-1])
        }
        let parmas={
          org_id_list:lsarr,
          org_type:org_type
        }
        let url='/sys/report_assist_new/case_list?tags='+this.tags;
        this.$api.post(url,parmas)
        .then(data=>{
          this.Case = [];
          if(data.data&&data.data.length){
            this.Case = data.data;
            this.submitCase = [];
            if (this.Case.length) {
              this.Case.unshift({case_name: '全部', id: 'all'});
              this.submitCase.push('all');
            }
            this.allCaseArr = this.Case.map(x => {
              return x.id
            });
            this.allCaseArr = this.allCaseArr.filter(x => {
              return x != 'all'
            });

          } else{
            this.$message.warning('该企业下无案场!');
            this.Case = [];
            this.submitCase = null;
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
           console.log(err)
          this.$message.warning('该企业下无案场!');
          this.Case = [];
          this.submitCase = null;
        })
      },

      //案场change事件
      CaseChange(val){
        //已经选择了全部，想要排除掉all这个选项
        if(val[0] == 'all' && val.length != 1){
          this.submitCase = this.submitCase.filter(x=>x != 'all')
          this.isAllCase = false
        }else if(val.includes('all')){//点击了全部，干掉其他选中的部分
          this.submitCase = ['all'];
          this.isAllCase = true;
        }else{
          this.isAllCase = false
        }
        this.dataIsChange = true//改变按钮状态
      },

      //案场选择改变
      CaseVisibleChange(val) {
        if (!val) {
          if (this.submitCase == null) {
            this.$message.warning('该企业下无案场！');
            return
          }
          if (!this.submitCase.length) {
            this.$message.warning('请选择至少一个案场！');
            if (this.Case.length) {
              this.caseFirstTry()
            }
            return
          }
          this.dataIsChange = true//改变按钮状态
        }
      },
      //案场多选删除事件
      CaseClick(){
        if(this.submitCase.length==0) {
          this.$message.warning('请至少选择一个案场!');
          this.caseFirstTry()
        }
        this.dataIsChange = true//改变按钮状态
      },

      //日期change事件
      dayChange(val){
        this.dataIsChange = true//改变按钮状态
      },
      //时间change事件
      timeChange(val){
        if(val[0] == val[1]){
          this.$message.warning('起始时间不得等于终止时间')
          this.datetimeval.hm = ['00:00','23:59']
        }
        this.TimeFast='';
        this.dataIsChange = true//改变按钮状态
      },
      //快速选择时间change事件
      TimaFastChange(val){
        this.dataIsChange = true//改变按钮状态
        switch (val) {
          case "min30": {
            let str_hm = moment().subtract(30, 'minutes').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "hour1": {
            let str_hm = moment().subtract(1, 'hours').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "hour2": {
            let str_hm = moment().subtract(2, 'hours').format('HH:mm');
            let end_hm = moment().format('HH:mm');
            this.datetimeval.hm = [str_hm, end_hm];
            break;
          }
          case "today": {
            this.datetimeval.hm = ["00:00", "23:59"];
            break;
          }
        }
      },

      //案场初始化
      caseFirstTry(){
        this.submitCase = ['all']
        this.isAllCase = true;
      },

      companyVisibleChange(val){
        if(!val){
          this.companyChange();
        }
      },
      //移除tag时触发
      companyRemoveTag(val){
        this.$nextTick(()=>{
          if(this.company_id_arr.length) this.companyChange()
        })
      },
      //企业选择改变
      companyChange(){
        if(!this.company_id_arr.length) {
          this.$message.warning('请至少选择一个企业');
          this.Case=[];
          this.submitCase=[];
          this.$Bus.$emit('Remove');
          return
        }
        this.dataIsChange = true//改变按钮状态
        this.$Bus.$emit('Loading',true);
        let company_id_arr = this.company_id_arr.map(x => {
          return x.slice(-1)[0]
        });
        this.company_id = company_id_arr.join(',')
        this.caseFirstTry();
        this.getCaseApi(this.company_id_arr);
      },
      //点击查询按钮
      queryData(){
        if(!this.company_id_arr.length){
          this.$message.warning('请至少选择一个企业')
          return
        }
        let submitdata={};
        submitdata.start_hm=this.datetimeval.hm[0];
        submitdata.end_hm=this.datetimeval.hm[1];
        submitdata.start_day=this.datetimeval.day[0];
        submitdata.end_day=this.datetimeval.day[1];
        submitdata.case_id_list = this.isAllCase ? this.allCaseArr : this.submitCase
        // console.log(submitdata, 'submitdata');
        this.$Bus.$emit('UpCondition',submitdata,this.dataIsChange)
        this.dataIsChange = false//改变按钮状态
      },
    },
    watch: {
      isDisabledTims(val){
        if(true){
          this.datetimeval.hm=["00:00","23:59"];
          this.TimeFast='today';
        }
      }
    }
  };

</script>
